//
//  XWebViewController.m
//  yongfatouzi
//
//  Created by Hongshuo Xiao on 2017/12/30.
//  Copyright © 2017年 YFTZCompany. All rights reserved.
//

#import "XWebViewController.h"

//handler name
static NSString *baseMessagehandler = @"baseMessagehandler";

//implemented method list
static NSString *closeWebView = @"closeWebView";
static NSString *goBack = @"goBack";
static NSString *shareEnt = @"shareEnt";
static NSString *Business = @"Business";
static NSString *Bindex = @"Bindex";
static NSString *getGifts = @"getGifts";

@interface XWebViewController ()<WKNavigationDelegate, WKUIDelegate>

//UI
@property (nonatomic, strong) UIProgressView  *progressView;
@property (nonatomic, strong) UIView          *errorView;

//data
@property (nonatomic, copy)   NSString *urlString;
@property (nonatomic, strong) NSURL    *url;
@property (nonatomic, strong) NSURLRequest *request;
@property (nonatomic, copy)   NSString *htmlString;
@property (nonatomic, strong) NSURL    *baseURL;

//message
@property (nonatomic, strong) NBLMessage *message;

@end

@implementation XWebViewController

- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_webView removeObserver:self forKeyPath:@"canGoBack"];
    [_webView removeObserver:self forKeyPath:@"title"];
}

- (instancetype)initWithURLString:(NSString *)urlString
{
    self = [super init];
    if (self) {
        _urlString = urlString;
    }
    
    return self;
}


- (instancetype)initWithURL:(NSURL *)url
{
    self = [super init];
    if (self) {
        _url = url;
    }
    
    return self;
}


- (instancetype)initWithRequest:(NSURLRequest *)request
{
    self = [super init];
    if (self) {
        _request = request;
    }
    
    return self;
}


- (instancetype)initWithHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
{
    self = [super init];
    if (self) {
        _htmlString = string;
        _baseURL = baseURL;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self navigation];//自定义导航栏
    [self initUI];
    [self registerMessageHandler];
    [self addObserver];
    [self loadPage];
    // Do any additional setup after loading the view.
}

- (void)navigation
{
    [[super btnBack] setHidden:NO];
    [[super btnBack] addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [[super labTitle] setHidden:NO];
    [super labTitle].frame = CGRectMake(100, SafeAreaTopHeight-44, SCREEN_WIDTH-200, 44);
    
    //保存按键
    btnSave = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnSave.frame = CGRectMake(40, SafeAreaTopHeight-44, 60, 44);
    [btnSave setTitle:NSLocalizedStringFromTableInBundle(@"Close", @"Localizable", [TCUtils bundle], nil) forState:UIControlStateNormal];
    [btnSave setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnSave.titleLabel.font = [UIFont systemFontOfSize:16];
    btnSave.hidden=YES;
    [btnSave addTarget:self action:@selector(closeSelf) forControlEvents:UIControlEventTouchUpInside];
    [[super navigationBackground] addSubview:btnSave];
    
    if([self.type isEqual:@"article"]){
        if ([self.typeNot integerValue] >=0) {
            _btnSubmit = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            _btnSubmit.frame = CGRectMake(SCREEN_WIDTH-50, SafeAreaTopHeight-44, 44, 44);
            _btnSubmit.hidden = NO;
            [_btnSubmit setTitleColor:KDarkColor forState:UIControlStateNormal];
            [_btnSubmit setBackgroundImage:[UIImage imageNamed:@"wenzhangSave"]  forState:UIControlStateNormal];
            [_btnSubmit addTarget:self action:@selector(clickTopRight) forControlEvents:UIControlEventTouchUpInside];
            [[super navigationBackground] addSubview:_btnSubmit];
        }else{
            
        }
    }
}

-(void)clickTopRight{
//    NSMutableDictionary* dicUser = [TCUtils getUserDefaultDic];
//    NSMutableDictionary *dic = [@{} mutableCopy];
//    [dic setObject:[dicUser objectForKey:USER_DATA_KEY_USERID] forKey:@"user_id"];
//    [dic setObject:@"add" forKey:@"mode"];
//    [dic setObject:self.key_id forKey:@"key_id"];
//    [LoadingHelper showLoadingWithView:self.view];
//    [ApiAllManager saveArtick:dic andBlock:^(NSError *error,NSString *msg) {
//        if (msg != nil) {
//            [TCUtils showAlertViewWithTitle:NSLocalizedStringFromTableInBundle(@"Prompt", @"Localizable", [TCUtils bundle], nil) message:msg delegate:self view:self.view];
//        }else if(error != nil){
//            
//        }else{
//            [TCUtils showAlertViewWithTitle:NSLocalizedStringFromTableInBundle(@"Prompt", @"Localizable", [TCUtils bundle], nil) message:@"收藏成功" delegate:self view:self.view];
//        }
//    }];
}

#pragma mark - Getter

- (WKWebView *)webView
{
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight) configuration:configuration];
//        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    
    return _webView;
}


- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, self.view.frame.size.width, 0)];
        _progressView.tintColor = KStandardColor;
        _progressView.trackTintColor = [UIColor clearColor];
        _progressView.hidden = YES;
    }
    
    return _progressView;
}

- (UIView *)errorView
{
    if (!_errorView) {
        _errorView = [[UIView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight)];
//        _errorView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _errorView.backgroundColor = [UIColor whiteColor];
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshPage)];
        _errorView.userInteractionEnabled = YES;
        [_errorView addGestureRecognizer:gesture];
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 140, 60)];
        [button setTitle:NSLocalizedStringFromTableInBundle(@"Tap to reload", @"Localizable", [TCUtils bundle], nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(refreshPage) forControlEvents:UIControlEventTouchUpInside];
        button.center = _errorView.center;
        [_errorView addSubview:button];
    }
    
    return _errorView;
}

#pragma mark - Action

- (void)backAction
{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        [self closeSelf];
    }
}


- (void)closeSelf
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private

- (void)initUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
}

- (void)setErrorViewHidden:(BOOL)hidden
{
    if (hidden) {
        [self.errorView removeFromSuperview];
    } else {
        [self.view addSubview:self.errorView];
    }
}


- (void)addObserver
{
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
    [self.webView addObserver:self
                   forKeyPath:@"canGoBack"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:NULL];
}


- (void)loadPage
{
    if (self.urlString.length > 0) {
        [self loadURLString:self.urlString];
    } else if (self.url) {
        [self loadURL:self.url];
    } else if (self.request) {
        [self loadRequest:self.request];
    } else if (self.htmlString.length > 0 || self.baseURL) {
        [self loadHTMLString:self.htmlString baseURL:self.baseURL];
    }
}


- (void)refreshPage
{
    if (self.webView.URL) {
        [self.webView reload];
    } else {
        [self loadPage];
    }
}


- (void)hideProgress
{
    self.progressView.hidden = YES;
    [self.progressView setProgress:0 animated:NO];
}


- (void)updateProgress:(float)progress
{
    self.progressView.hidden = NO;
    [self.progressView setProgress:progress animated:YES];
}


- (void)loadURLString:(NSString *)urlString
{
    [self loadURL:[NSURL URLWithString:urlString]];
}


- (void)loadURL:(NSURL *)url
{
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [self loadRequest:request];
}


- (void)loadRequest:(NSURLRequest *)request
{
    [self.webView loadRequest:request];
}


- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL
{
    [self.webView loadHTMLString:string baseURL:baseURL];
}

#pragma mark - Public

- (void)registerMessageHandler
{
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:baseMessagehandler];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:shareEnt];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:Business];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:Bindex];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:getGifts];
}


- (BOOL)dealWithMessage:(WKScriptMessage *)message
{
    BOOL canDeal = NO;
    if ([message.body isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)message.body;
        self.message = [[NBLMessage alloc] init];
        self.message.methodName = dic[methodNameKey];
        self.message.params = dic[paramsKey];
        self.message.callbackMethod = dic[callbackMethodKey];
    }
    
    if ([message.name isEqualToString:baseMessagehandler]) {
        if ([self.message.methodName isEqualToString:closeWebView]) {
            //close webview
            [self closeSelf];
            canDeal = YES;
        } else if ([self.message.methodName isEqualToString:goBack]) {
            //go back
            [self backAction];
            canDeal = YES;
        }
    }else if([message.name isEqual:shareEnt]){
        NSLog(@"1111");
    }else if ([message.name isEqual:Business]){
        [self closeSelf];
        
    }else if ([message.name isEqual:Bindex]){
        NSUserDefaults* user = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.PlusFo"];
        if ([[user objectForKey:@"group.com.PlusFo.LoginState"] isEqualToString:@"0"])
        {
            [TCUtils showAlertViewWithTitle:NSLocalizedStringFromTableInBundle(@"Prompt", @"Localizable", [TCUtils bundle], nil) message:NSLocalizedStringFromTableInBundle(@"Login1", @"Localizable", [TCUtils bundle], nil) delegate:self view:self.view];
            return canDeal;
        }
//        GongxianJiluViewController *renameNickController = [[GongxianJiluViewController alloc]init];
//        [self.navigationController pushViewController:renameNickController animated:YES];
    }else if ([message.name isEqual:getGifts]){
        NSUserDefaults* user = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.PlusFo"];
        if ([[user objectForKey:@"group.com.PlusFo.LoginState"] isEqualToString:@"0"])
        {
            [TCUtils showAlertViewWithTitle:NSLocalizedStringFromTableInBundle(@"Prompt", @"Localizable", [TCUtils bundle], nil) message:NSLocalizedStringFromTableInBundle(@"Login1", @"Localizable", [TCUtils bundle], nil) delegate:self view:self.view];
            return canDeal;
        }
//        MineGiftsViewController *renameNickController = [[MineGiftsViewController alloc]init];
//        [self.navigationController pushViewController:renameNickController animated:YES];
    }
    
    if (canDeal && self.message.callbackMethod.length > 0) {
        //callback js
    }
    
    return canDeal;
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webView) {
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            CGFloat progress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
            if (progress == 1) {
                [self hideProgress];
            } else {
                [self updateProgress:progress];
            }
        } else if ([keyPath isEqualToString:@"canGoBack"]) {
            if (self.webView.canGoBack && self.navigationItem.leftBarButtonItems.count != 2) {
                btnSave.hidden=NO;
    }
        } else if ([keyPath isEqualToString:@"title"]) {
            [super labTitle].text = self.webView.title;
        }
    }
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [self hideProgress];
    [self setErrorViewHidden:NO];
    self.title = NSLocalizedStringFromTableInBundle(@"Failed to load", @"Localizable", [TCUtils bundle], nil);
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    [self hideProgress];
    [self setErrorViewHidden:YES];
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    [self dealWithMessage:message];
}

#pragma mark - WKUIDelegate

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedStringFromTableInBundle(@"Prompt", @"Localizable", [TCUtils bundle], nil) message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:NSLocalizedStringFromTableInBundle(@"Confirm", @"Localizable", [TCUtils bundle], nil) style:UIAlertActionStyleDefault handler:nil];
    [alertVC addAction:confirmAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    completionHandler();
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
